package com.gf.common;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.gf.pf.model.User;

/**
 * @describe Session拦截器
 * @author   sss
 * @date     2014年9月2日
 */
public class SessionInterceptor extends HandlerInterceptorAdapter {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(SessionInterceptor.class);
	
	/**
	 * 用户登录键值
	 */
	private final String USER_KEY = "user";

	/**
	 * 检查session中的登录信息，区别ajax
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		LOGGER.info("session检查");
		User user = (User) request.getSession().getAttribute(this.USER_KEY);
		if (user == null) {
			if (isAjax(request)) {
				response.setHeader("Cache-Control", "no-cache");
				response.setHeader("Content-Type", "text/json;charset=utf-8");
				response.setCharacterEncoding("UTF-8");
				return false;
			} else {
				response.sendRedirect(request.getContextPath() + "/jlogin");
			}
		}
		return super.preHandle(request, response, handler);
	}

	/**
	 * 处理成功才进入post处理
	 */
	@Override
	public void postHandle(HttpServletRequest request,HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		super.postHandle(request, response, handler, modelAndView);
	}

	/**
	 * 处理完后进入，不论是否抛除异常
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		super.afterCompletion(request, response, handler, ex);
	}
	
	/**
	 * 
	 * @describe 判断是否是ajax请求
	 * @param request
	 * @return
	 */
	private boolean isAjax(HttpServletRequest request) {
		String xrw = request.getHeader("X-Requested-With");
		if ("XMLHttpRequest".equalsIgnoreCase(xrw)) {
			return true;
		}
		return false;
	}
}
